<template>
	<a-modal v-bind="option" class="vacancy-statistics-table">
		<vxe-grid ref="grid" v-bind="gridOptions" :row-config="{keyField: 'id'}" row-id="id">
			<template #couponType="{row}">
				{{ row.couponName }}
			</template>
			<template #price="{row}">
				<span v-if="row.couponType === 1">{{ row.couponAmount }}元</span>
				<span v-else>{{ row.couponAmount }}%</span>
			</template>
			<template #useRestriction="{row}">
				{{ row.isSuperUse === 0 ? '不可叠加使用' : '可叠加使用' }}
			</template>
			<template #time="{row}">{{ row?.effectiveBeginTime?.split(' ')[0] }}-{{ row?.effectiveEndTime?.split(' ')[0] }}</template>
		</vxe-grid>
		<template #footer>
			<div style="display: flex; justify-content: space-between">
				<span style="margin-right: auto">
					待收金额
					<span v-color="{color: 'primary'}">
						{{ amountCollected?.toFixed(2) || 0 }}
					</span>
					元，优惠
					<span v-color="{color: 'primary'}">
						{{ discountMoney?.toFixed(2) || 0 }}
					</span>
					元
				</span>
				<a-button key="submit" type="primary" style="margin-left: auto" @click="submit(1)">确认使用</a-button>
			</div>
		</template>
	</a-modal>
</template>

<script setup lang="ts">
	import {reactive, toRef, ref, watch, nextTick, computed} from 'vue'
	import {VxeGridProps, VxeGridInstance} from 'vxe-table'
	import {activityDistributeList, getCouponViewAfterUserCoupon} from '@/api/bill'
	import {message} from 'ant-design-vue'
	const emit = defineEmits(['update:visible', 'success', 'CouponViews'])
	const props = defineProps<{
		/** 弹窗展示 */
		visible: boolean
		currentRow: any // 当前账单
		checkList: any // 当前账单选中的优惠券id
		checkCouponListExceptSelf: Array<string>
	}>()
	const loadings = reactive({
		save: false,
		search: false
	})
	const grid = ref<VxeGridInstance>()
	// 判断可否叠加使用的勾选
	const unquiState = ref<string | number>('noState')
	// 如果其他账单选中了优惠券 那么这个条目中的优惠券需要禁用掉
	const disabledCheckList = computed(() => {
		return props.checkCouponListExceptSelf
	})

	const currentData = reactive<any>({
		row: {},
		checkList: []
	})
	// 待收金额
	const amountCollected = computed(() => {
		return (props.currentRow?.beginMoney || 0) - discountMoney.value
	})
	// 优惠金额
	const discountMoney = ref(0)

	const checkIds = computed(() => {
		return currentData.checkList.map(item => item.id)
	})

	/** 弹窗配置 */
	const option = reactive({
		width: 950,
		title: '选择优惠券',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel: () => onClose()
	})

	const onClose = () => {
		emit('update:visible', false)
	}

	const gridOptions = reactive<VxeGridProps>({
		height: 400,
		showOverflow: true,
		rowConfig: {
			isHover: true
		},
		// @ts-ignore
		onCheckboxChange({checked, row}) {
			// 因为这里回调过来的records可能会包含其他账单已经勾选过的优惠券 这里要单独的做处理
			if (checked) {
				currentData.checkList.push(row)
			} else {
				if (currentData.checkList.map(i => i.id).includes(row.id)) {
					currentData.checkList = currentData.checkList.filter(i => i.id !== row.id)
				}
			}
			if (currentData.checkList.length) {
				submit()
				unquiState.value = currentData.checkList[0].isSuperUse
			} else {
				discountMoney.value = 0
				unquiState.value = 'noState'
			}
		},
		columns: [
			{
				width: 80,
				align: 'center',
				type: 'checkbox',
				title: '选择'
			},
			{
				title: '优惠券类型',
				minWidth: 180,
				align: 'center',
				slots: {
					default: 'couponType'
				}
			},
			{
				title: '优惠折扣',
				minWidth: 180,
				align: 'center',
				slots: {
					default: 'price'
				}
				// field: 'price'
			},
			{
				title: '使用限制',
				minWidth: 180,
				align: 'center',
				slots: {
					default: 'useRestriction'
				}
			},
			{
				title: '有效期',
				minWidth: 280,
				align: 'center',
				slots: {
					default: 'time'
				}
			}
		],
		checkboxConfig: {
			showHeader: false,
			checkMethod: ({row}) => {
				if (0 === unquiState.value) {
					// 不可叠加 && 其他优惠券没有选中
					return checkIds.value.includes(row.id) && !disabledCheckList.value.includes(row.id)
				} else {
					// 可以使用 && 可以叠加 || 无状态 && 其他优惠券没有选中
					return 1 === row.isEnableUse &&  (unquiState.value === row.isSuperUse || 'noState' === unquiState.value) && !disabledCheckList.value.includes(row.id)
				}
			}
		}
	})

	// 获取列表
	const getList = () => {
		const obj = {
			phone: currentData?.row?.phone,
			feeSubjectIds: [currentData?.row?.feeSubjectId],
			contractId: currentData?.row?.bizId
		}
		activityDistributeList(obj).then(res => {
			// 获取待核销的优惠券
			gridOptions.data = res.data.couponRenterList.filter(item => item.isEnableUse === 1)

			if (checkIds.value) {
				nextTick(() => {
					// 回显当前选中和别的优惠券选中的(别的优惠券选中的需要禁用掉)
					const checkList = res.data.couponRenterList.filter(
						i => checkIds.value.includes(i.id) || disabledCheckList.value.includes(i.id)
					)
					grid?.value?.setCheckboxRow(checkList, true)

					if (currentData.checkList.length) {
						unquiState.value = currentData.checkList[0].isSuperUse
					} else {
						unquiState.value = 'noState'
					}
				})
			}
		})
	}

	const submit = async (e?: number) => {
		loadings.save = true
		const params = {
			billDetailCouponItems: [
				{
					billDetailId: currentData?.row?.id,
					distributeCouponIds: checkIds.value
				}
			],
			contractId: currentData?.row?.bizId
		}

		let res: any
		try {
			res = await getCouponViewAfterUserCoupon(params)
			if (e === 1) {
				message.success('使用成功')
				onClose()
				emit('success', true, {key: currentData?.row?.id, list: currentData.checkList, ids: checkIds.value})
			}
		} catch (error) {
			// console.error(error)
		} finally {
			loadings.save = false
		}

		discountMoney.value = res?.data?.totalReduceMoney || 0
	}

	watch(
		() => props.visible,
		newVal => {
			if (newVal) {
				currentData.row = props.currentRow
				currentData.checkList = props.checkList
				getList()
				submit()
			}
		}
	)
</script>

<style scoped></style>
